package com.rapida.plugin;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;

import java.util.ArrayList;
import java.util.List;

public class PluginManager {
	private static PluginManager mInst;
	private Context mContext;
	private PackageManager mPackageManager;
	private String mPluginPackage;
	private ArrayList<PluginInfo> mPlugins = new ArrayList<PluginInfo>();

	public static PluginManager get(Context context) {
		if (mInst == null) {
			mInst = new PluginManager(context);
		}
		return mInst;
	}

	private PluginManager(Context context) {
		mContext = context;
		mPluginPackage = mContext.getPackageName() + ".";
		mPackageManager = mContext.getPackageManager();
	}

	public void searchPlugin() {
		final Intent pluginIntent = new Intent(Intent.ACTION_MAIN, null);
		pluginIntent.addCategory(Intent.CATEGORY_LAUNCHER);
		List<PackageInfo> packages = mPackageManager.getInstalledPackages(PackageManager.PERMISSION_GRANTED);
		mPlugins.clear();
		for (PackageInfo info : packages) {
			if (info.packageName.startsWith(mPluginPackage)) {
				PluginInfo plugin = new PluginInfo();
				plugin.packageName = info.packageName;
				plugin.versionCode = info.versionCode;
				plugin.versionName = info.versionName;
				plugin.pluginName = info.applicationInfo.loadLabel(mPackageManager).toString();
				plugin.pluginIcon = info.applicationInfo.loadIcon(mPackageManager);
				plugin.pluginPath = info.applicationInfo.sourceDir;
				try {
					ApplicationInfo appInfo = mPackageManager.getApplicationInfo(info.packageName, PackageManager.GET_META_DATA);
					plugin.pluginEntry = appInfo.metaData.getString("com.rapida.plugin.entry");
					mPlugins.add(plugin);
				} catch (Exception e) {
				}
			}
		}
	}

	public ArrayList<PluginInfo> getPluginInfo() {
		return mPlugins;
	}
}
